package com.xunjing.order.config.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author ZYT
 * @Date 2024-04-01 14:33
 * @Version 1.0
 * @Describe 按flag精确分表
 */
@Component
public class FlagPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    private static ShardingAlgorithmReload shardingAlgorithmReload;
    @Autowired
    public void setShardingAlgorithmReload(ShardingAlgorithmReload shardingAlgorithmReload){
        FlagPreciseShardingAlgorithm.shardingAlgorithmReload = shardingAlgorithmReload;
    }
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        //根据分表标识
        String flag =  preciseShardingValue.getValue();
        // 定义匹配模式
        String pattern = "^(\\d{4})(0[1-9]|1[0-2])$";
        // 编译正则表达式
        Pattern r = Pattern.compile(pattern);
        // 创建 Matcher 对象
        Matcher m = r.matcher(flag);
        if (!m.find()) throw new IllegalArgumentException("传入不符合规则");

        //组合真正的表名
        String preciseTable = preciseShardingValue.getLogicTableName() + "_" + flag;
        //判断缓存里是否包含分表
        if(collection.contains(preciseTable)){
            return preciseTable;
        }else{
            // 检查分表获取的表名不存在，需要自动建表
            boolean isSuccess = shardingAlgorithmReload.createShardingTable(preciseShardingValue.getLogicTableName(), preciseTable);
            if (isSuccess) {
                //添加缓存
                collection.add(preciseTable);
                return preciseTable;
            } else {
                // 如果建表失败，返回逻辑空表(无法插入数据)
                throw new IllegalArgumentException("未找到匹配的数据表");
            }
        }
    }
}
